/*
 *  Copyright (C) 2010 Glauco
 * 
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 * 
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 * 
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.balisunrise.swing.transaction.panel.actions;

import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JTable;
import javax.swing.KeyStroke;

/**
 *
 * @author Glauco
 */
public class TableEnterAction extends AbstractAction{

    JTable table;

    int rows, cols, row, col;

    @SuppressWarnings("LeakingThisInConstructor")
    public TableEnterAction(JTable table) {
        this.table = table;
        table.getInputMap().put(KeyStroke.getKeyStroke("ENTER"), "handleEnter");
        table.getActionMap().put("handleEnter", this);
    }

    public void actionPerformed(ActionEvent e) {
        rows = table.getRowCount();
        cols = table.getColumnCount();
        row = table.getSelectedRow();
        col = table.getSelectedColumn();
        //System.out.println(this.toString());
        if(!table.isEditing())
            nextColumn();
    }

    private void nextColumn(){

        if(col < 0 || row < 0){
            col = 0;
            row = 0;
            selectNextColumn();
            return ;
        }

        col++;
        
        if (col >= cols){
            nextRow();
            return ;
        }

        if (!table.isCellEditable(row, col)){
            nextColumn();
            return ;
        }
        
       selectNextColumn();
    }

    private void nextRow(){

        if (row == rows-1){
            focusOut();
            return ;
        }

        row++;

        int nextRowCol = 0;

        while(!table.isCellEditable(row, nextRowCol)){
            nextRowCol++;
            if(nextRowCol >= cols){
                nextRowCol = 0;
                break;
            }
        }

        col = nextRowCol;
        selectNextColumn();
    }

    private void focusOut(){
        table.transferFocus();
    }

    private void selectNextColumn(){
        table.changeSelection(row, col, false, false);
        //table.editCellAt(row, col);
    }

    @Override
    public String toString() {
        return "Values: " + rows + "," + cols + "," + row + ","+ col;
    }


}
